package com.pig4cloud.pig.module.controller.devices;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.devices.Devices;
import com.pig4cloud.pig.module.api.entity.devices.DevicesEggCell;
import com.pig4cloud.pig.module.api.entity.devices.DevicesEggGetRecord;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.service.devices.IDevicesEggCellService;
import com.pig4cloud.pig.module.service.devices.IDevicesEggGetRecordService;
import com.pig4cloud.pig.module.service.devices.IDevicesService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 设备列Controller
 *
 * @author ruoyi
 * @date 2022-01-06
 */
@Validated
@Api(value = "设备列控制器", tags = {"设备列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/devices")
@TableName("devices")
public class DevicesController {

    private final IDevicesService devicesService;
	private final IEstateService estateService;
	private final IDevicesEggCellService devicesEggCellService;

	private final IDevicesEggGetRecordService devicesEggGetRecordService;
	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;


    /**
     * 查询设备列列表
     */
    @ApiOperation("查询设备列列表")
    @PreAuthorize("@pms.hasPermission('module:devices:list')")
    @GetMapping("/list")
    public TableDataInfo<Devices> list(@Validated Devices devices) {
        QueryWrapper<Devices> qw = new QueryWrapper<>();
        if(devices.getEstateId()!=null){
        	qw.eq("estate_id",devices.getEstateId());
		}

        if(devices.getState() != null){
        	qw.eq("state",devices.getState());
		}

        if(StrUtil.isNotEmpty(devices.getDeviceSn())){
        	qw.like("device_sn",devices.getDeviceSn()).or().like("device_name",devices.getDeviceSn());
		}

        TableDataInfo<Devices> td = PageUtils.buildDataInfo(devicesService.page(PageUtils.buildPage(),qw));
        List<Devices> list = td.getData();
        for (Devices devices1 : list){
        	if(StrUtil.isNotEmpty(devices1.getQrCode())){
				devices1.setQrCode(imgUrl + devices1.getQrCode());
			}
        	QueryWrapper<DevicesEggCell> qwCell = new QueryWrapper<>();
			qwCell.eq("device_id",devices1.getId());
			qwCell.eq("state",1);
        	long count = devicesEggCellService.count(qwCell);
			devices1.setCellCount(count);

		}
        return td;
    }

	@ApiOperation("查询统计数据")
	@PreAuthorize("@pms.hasPermission('module:devices:list')")
	@GetMapping("/tongji/list")
	public TableDataInfo<Devices> tongjiList(@Validated Devices devices) {
		QueryWrapper<Devices> qw = new QueryWrapper<>();
		if(devices.getDeviceNo()!=null){
			qw.eq("device_sn",devices.getDeviceSn());
		}

		if(devices.getDeviceName() != null){
			qw.eq("device_name",devices.getDeviceName());
		}

		if(StrUtil.isNotEmpty(devices.getEstateName())){
			qw.eq("estate_name",devices.getEstateName());
		}
		TableDataInfo<Devices> td = PageUtils.buildDataInfo(devicesService.page(PageUtils.buildPage(),qw));
		List<Devices> list = td.getData();
		for (Devices devices1 : list){
			QueryWrapper<DevicesEggCell> qwCell = new QueryWrapper<>();
			qwCell.select("id");
			qwCell.eq("device_id",devices1.getId());
			qwCell.eq("state",1);
			long count = devicesEggCellService.count(qwCell);
			devices1.setCellCount(count);
			QueryWrapper<DevicesEggGetRecord> qw2 = new QueryWrapper<>();
			if(StrUtil.isNotEmpty(devices.getBeginDate())){
				qw2.between("create_time", devices.getBeginDate() + " 00:00:00",devices.getEndDate() + " 23:59:59");
			}
			qw2.eq("device_id",devices1.getId());
			List<DevicesEggGetRecord> list1=devicesEggGetRecordService.list(qw2);
			int tissueTotal=0;
			int WashingPowder=0;
			int soap=0;
			for (DevicesEggGetRecord list2:list1){
				if(list2.getCellType()==1){
					tissueTotal+=1;
				}
				if(list2.getCellType()==2){
					WashingPowder+=1;
				}
				if(list2.getCellType()==3){
					soap+=1;
				}
			}
			devices1.setTissueTotal(tissueTotal);
			devices1.setWashingPowder(WashingPowder);
			devices1.setSoap(soap);
		}
		return td;
	}
    /**
     * 导出设备列列表
     */
    @ApiOperation("导出设备列列表")
    @PreAuthorize("@pms.hasPermission('module:devices:export')")
    @SysLog("设备列")
    @GetMapping("/export")
    public List export(@Validated Devices devices) {
        List<Devices> list = devicesService.list();
        // ExcelUtil<Devices> util = new // ExcelUtil<Devices>(Devices.class);
        return  list;// util.exportExcel(list, "设备列");
    }

    /**
     * 获取设备列详细信息
     */
    @ApiOperation("获取设备列详细信息")
    @PreAuthorize("@pms.hasPermission('module:devices:query')")
    @GetMapping("/{id}")
    public R<Devices> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Devices devices = devicesService.getById(id);
        return R.ok(devices);
    }

    /**
     * 新增设备列
     */
    @ApiOperation("新增设备列")
    @PreAuthorize("@pms.hasPermission('module:devices:add')")
    @SysLog("设备列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Devices devices) {
		Estate estate = estateService.findById(devices.getEstateId());
		if(estate!=null){
			devices.setEstateName(estate.getEstateName());
			devices.setPropertyId(estate.getPropertyId());
		}

		boolean bl = devicesService.save(devices);
        return R.okByRow(bl);
    }


	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:devices:edit')")
	public R<Void> resetQrCode(@RequestBody Devices devices) {
		if(devices.getId()!=null){
			try{
				devices = devicesService.getById(devices.getId());
				if(devices!=null){
					String qrcode = "";
					String fileName = "device_qr_" + devices.getDeviceSn() + ".jpg";
//					String content = "{\"qrtype\":\"device\",\"sn\":\"" + devices.getDeviceSn() + "\"}";
					String content = "https://www.sdyuedou.com/wxmini/takeup/device?id=" + devices.getId();
//					Aes aes = new Aes();
					int upload_type = 0;//FileUploadUtils.TYPE_DEVICE_PHOTOS;
//					content = aes.encrypt(content);
					System.out.println("content:  "+ content);
					String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, "设备编号：" + devices.getDeviceSn(),
						null, uploadPath +"/"+img_key, true, fileName, upload_type);
					qrcode = img_key;
					devices.setQrCode(qrcode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (devicesService.updateById(devices)) {
				return R.ok();
			}
		}
		return R.failed();
	}

    /**
     * 修改设备列
     */
    @ApiOperation("修改设备列")
    @PreAuthorize("@pms.hasPermission('module:devices:edit')")
    @SysLog("设备列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Devices devices) {
		Estate estate = estateService.findById(devices.getEstateId());
		if(estate!=null){
			devices.setEstateName(estate.getEstateName());
			devices.setPropertyId(estate.getPropertyId());
		}
        return R.okByRow(devicesService.updateById(devices) ? 1 : 0);
    }

    /**
     * 删除设备列
     */
    @ApiOperation("删除设备列")
    @PreAuthorize("@pms.hasPermission('module:devices:remove')")
    @SysLog("设备列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(devicesService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
